﻿using UnityEngine;
using System.Collections;

public class Shooter : TouchScript {
	public GameObject bulletPreFab;
	public float FireRate = 0.5f;
	public float fireTimer = 0.0f;
	float colourTimer = 5.0f;
	public float ColourChangeFrequency = 2.0f;
	bool Selected = false;
	private int selectedFingerId = -1;
	Color currentColour = Color.red;
	// Use this for initialization
	void Start () {
		colourTimer = ColourChangeFrequency;
	}
	
	// Update is called once per frame
	void Update () {

		fireTimer -= Time.deltaTime;
		colourTimer -= Time.deltaTime;
		if(fireTimer < 0.0f)
		{ Fire (); fireTimer = FireRate; }
		if(colourTimer < 0.0f)
		{
			colourTimer = ColourChangeFrequency;
			switch(Random.Range(0,4))
			{
			case 0:
			default:
				currentColour = Color.red;
				break;
			case 1:
				currentColour = Color.blue;
				break;
			case 2:
				currentColour = Color.yellow;
				break;
			case 4:
				currentColour = Color.green;
				break;
			}
		}
	}
	public override void Move (Vector3 pos, TouchPhase phase, int fingerId)
	{
		//First Click on Object
		if(phase == TouchPhase.Began && this.collider2D.OverlapPoint(new Vector3(pos.x,pos.y)))
		{
			Debug.Log("Touched " + fingerId);
			Selected = true;
			selectedFingerId = fingerId;
		}
		else if(phase == TouchPhase.Ended && selectedFingerId == fingerId)
		{
			Debug.Log("Ended " + fingerId);
			Selected = false;
			selectedFingerId = -1;
		}
		//Dragging the Object Add the logic here
		if(Selected && selectedFingerId == fingerId)
			this.transform.position = new Vector3(pos.x,this.transform.position.y,this.transform.position.z);
		
	}
	void OnMouseDrag()
	{
		Vector3 hit = Camera.main.ScreenToWorldPoint(Input.mousePosition);
		this.transform.position = new Vector3(hit.x,this.transform.position.y,this.transform.position.z);
		
	}
	void Fire()
	{	Vector3 firePosition = new Vector3(this.transform.position.x ,this.transform.position.y + this.renderer.bounds.size.y/2,this.transform.position.z);
		GameObject bullet = (GameObject)Instantiate(bulletPreFab,firePosition,this.transform.rotation);
		bullet.GetComponent<Bullet>().col = currentColour;
		bullet.GetComponent<Bullet>().parent = this.transform.parent.parent;
	}
}
